package com.fs.uc.core.relationship;

import com.fs.uc.base.domain.Org;
import com.fs.uc.base.domain.OrgType;
import com.fs.uc.base.domain.Person;
import com.fs.uc.base.repo.PersonRepository;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

/**
 * @author 崔超
 * 2022/1/7
 */
@ApplicationScoped
class PersonRelationFetcher implements IRelationFetcher {
    @Inject
    PersonRepository personRepo;

    @Override
    public Long inWhichEnterprise(Long personId) {
        Org currentOrg = getCurrentOrg(personId);
        if (currentOrg.type == OrgType.Enterprise) {
            return currentOrg.id;
        }
        throw new RuntimeException("人员所属组织是园区主体");
    }

    @Override
    public Long inWhichPark(Long personId) {
        Org currentOrg = getCurrentOrg(personId);
        if (currentOrg.type == OrgType.Park) {
            return currentOrg.id;
        }
        if (currentOrg.parent == null) {
            throw new RuntimeException("人员所在企业没有上级园区主体");
        }
        return currentOrg.parent.id;
    }

    private Org getCurrentOrg(Long personId) {
        Person person = personRepo.getById(personId);
        Org currentOrg = person.currentOrg;
        if (currentOrg == null) {
            throw new RuntimeException("人员没有上级组织主体");
        }
        return currentOrg;
    }
}
